package cn.wsalix.code;

/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 简单封装Jackson，实现JSON String<->Java Object的Mapper.
 * 
 * 封装不同的输出风格, 使用不同的builder函数创建实例.
 * 
 * @author calvin
 */
public class XmlMapper {

	private static Logger logger = LoggerFactory.getLogger(XmlMapper.class);

	public static String toXml(Object obj) {
		XStream xstream = new XStream(new DomDriver("utf8"));
		xstream.processAnnotations(obj.getClass()); // 识别obj类中的注解
		/*
		 * // 以压缩的方式输出XML StringWriter sw = new StringWriter();
		 * xstream.marshal(obj, new CompactWriter(sw)); return sw.toString();
		 */
		// 以格式化的方式输出XML
		return xstream.toXML(obj);
	}

	public static <T> T toBean(String xmlStr, Class<T> cls) {
		XStream xstream = new XStream(new DomDriver());
		xstream.processAnnotations(cls);
		@SuppressWarnings("unchecked")
		T t = (T) xstream.fromXML(xmlStr);
		return t;
	}
}
